/**
 * 
 */
package com.xbang.attendance.web.action.system.personal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.xbang.attendance.entity.role.User;
import com.xbang.attendance.security.support.SecurityUserHolder;
import com.xbang.attendance.service.SystemService;
import com.xbang.attendance.utils.MD5;
import com.demo2do.lighturl.annotation.Action;
import com.xbang.core.struts.support.BaseActionSupport;
import com.xbang.core.utils.StringUtils;

/**
 * @author dev.zhang
 * 
 */
public class PersonlManager extends BaseActionSupport {

	private static final long serialVersionUID = 6245606726579886535L;

	@Autowired
	private SystemService systemService;

	private User user;

	@Action("/system/personal")
	public String index() throws Exception {

		user = SecurityUserHolder.getCurrentUser();

		return "index";
	}

	@Action("/system/personal/midfypassword")
	public String midfyPassward() throws Exception {
		reSetMessage();
		User tmpUser = SecurityUserHolder.getCurrentUser();
		user.setName(tmpUser.getName());
		
		String sentenceTemplate = "";

		if (StringUtils.isNotEmpty(user.getPassword()) && StringUtils.isNotEmpty(user.getRepassword()) && StringUtils.isNotEmpty(user.getNewPassword())) {
			if (user.getNewPassword().equals(user.getRepassword())) {
				//
				sentenceTemplate = "FROM User user WHERE user.id = :id AND user.password = :password";

				Map<String, Object> parameters = new HashMap<String, Object>();
				parameters.put("id", user.getId());
				parameters.put("password", MD5.crypt(user.getPassword()));

				List users = systemService.searchForList(sentenceTemplate, parameters);
				if (users == null || users.isEmpty()) {
					setErrorMessage("error.user.password.ori.error");
				} else {
					sentenceTemplate = "UPDATE USER SET password = :password  WHERE id = :id";

					parameters.clear();
					parameters.put("password", MD5.crypt(user.getNewPassword()));
					parameters.put("id", user.getId());
					systemService.execute(sentenceTemplate, parameters);
					setInfoMessage("info.user.password.modify.success");
				}
			} else {
				// error.
				setErrorMessage("error.user.password.duplicate.error");
			}
		} else {
			// //error..
			setErrorMessage("error.user.password.modify.password.null");
		}

		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>");
		return "index";
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

	/**
	 * @param user
	 *            the user to set
	 */
	public void setUser(User user) {
		this.user = user;
	}

}
